<template>
  <div class="left-tree" style="overflow:auto">
    <div class="tree-title">
      <el-input v-model="filterText" :size="size" type="text" style="width:95%" prefix-icon="el-icon-search"
                :placeholder="placeholder"
                clearable="clearable"></el-input>
    </div>
    <el-scrollbar>
      <el-tree class="tree-body"
               :data="envTree"
               style="height:800px;overflow-y:scroll;"
               :props="props"
               node-key="id"
               default-expand-all
               @node-click="goRouter"
               :filter-node-method="filterNode"
               highlight-current
               :expand-on-click-node="false"
               ref="tree"
      >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                        <i class="fa fa-folder-open-o" aria-hidden="true" v-if="!data.isLeaf"></i>
                        <i class="fa fa-window-maximize" aria-hidden="true" v-if="data.isLeaf"></i>
              <span v-if="!data.isChangeName">{{ node.label }}</span>
              <el-input v-else type="text" size="mini" v-model="data.label" style="width: 120px"
                        @keydown.enter.native="renameAfter(data)"></el-input>
              <span class="left-tree-btns">
                <el-dropdown trigger="click">
                  <span class="el-dropdown-link">
                    <i class="fa fa-ellipsis-h" aria-hidden="true"></i>
                  </span>
              <el-dropdown-menu size="small" slot="dropdown">
                <el-dropdown-item>
                  <i class="fa fa-edit" aria-hidden="true"></i>
                  <el-button type="text" size="mini" @click="() => rename(data)">重命名</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="!data.isLeaf">
                  <i class="fa fa-plus-square" aria-hidden="true"></i>
                  <el-button type="text" size="mini" @click="() => newFav(data)">新增收藏夹</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="!data.isLeaf">
                  <i class="icon iconfont icon-xinzeng"></i>
                  <el-button type="text" size="mini" @click="() => newEnv(data)">新增环境</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                   <i class="icon iconfont icon-shanchu"></i>
                   <el-button type="text" size="mini" @click="() => remove(data)">删除</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
        </span>
      </span>
      </el-tree>
    </el-scrollbar>
    <el-dialog title="新增环境" :visible.sync="editform.dialogFormVisible" width="60%" center>
      <el-row :gutter="24" align="center">
        <el-col :span="8">
          <el-form :model="treeForm">
            <el-form-item label="环境名称：" label-width="40%">
              <el-input v-model="treeForm.label"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-form :model="editform">
            <el-form-item label="方法：" label-width="40%">
              <el-select v-model.trim="editform.method" style="width:100%" filterable>
                <el-option v-for="item in methodList"
                           :key="item.keyc"
                           :label="item.keyc"
                           :value="item.keyc"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row :gutter="24" align="center">
        <el-col :span="8">
          <el-form :model="editform">
            <el-form-item label="协议：" label-width="40%">
              <el-input v-model="editform.svrType" readonly></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-form :model="editform">
            <el-form-item label="IP：" label-width="40%">
              <el-input v-model="editform.svrIp"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-form :model="editform">
            <el-form-item label="端口：" label-width="40%">
              <el-input v-model="editform.svrPort"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editform.dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickButton()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { mapState, mapActions } from 'vuex';
  import axios from '../../axios';
  import Api from '../../constants/Api';
  import {SUCCESS_CODE} from '../../constants/constant'
  export default {
    name: 'envTree',
    props: {
      data: {
        required: true,
        type: Object
      }, // 表单域（必传）
      placeholder: {
        type: String,
        default: '按条件筛选'
      }, // 占位文本
      size: {
        type: String,
        default: 'small'
      }, // 大小，可取值medium / small / mini
      clearable: {
        type: Boolean,
        default: true
      }, // 是否可以清空选项
      // 配置项
      props: {
        type: Object,
        default: () => {
          return {
            // ID字段名
            value: 'id',
            // 显示名称
            label: 'label',
            // 是否重命名
            isChangeName: false,
            // 是否是环境
            isLeaf: 'isLeaf',
            // 子级字段名
            children: 'children'
          };
        }
      }
    },
    data() {
      const data = [{
        id: 1,
        label: '一级 1',
        isChangeName: false,
        children: [{
          id: 4,
          label: '二级 1-1',
          isChangeName: false,
          children: [{
            id: 9,
            label: '三级 1-1-1',
            isChangeName: false,
            isLeaf: true,
          }, {
            id: 10,
            label: '三级 1-1-2',
            isChangeName: false,
          }]
        }]
      }, {
        id: 2,
        label: '一级 2',
        children: [{
          id: 5,
          label: '二级 2-1',
          isChangeName: false
        }, {
          id: 6,
          label: '二级 2-2'
        }]
      }];
      return {
        filterText: '',
        editform: {
          dialogFormVisible: false,
          // 协议类型
          svrType: 'HTTP',
          // 服务器IP
          svrIp: '',
          // 服务器IP
          svrPort: '',
          // 上一级ID
          parentId: '',
          // 自己的ID
          favId: '',
          // 模板ID
          tmplId: 'env',
          // 方法
          method: 'post',
        },
        treeForm: {
          id: 1000,
          label: '新建环境',
          favLabel: '新建收藏夹',
          isLeaf: false,
        },
        defualId: 1,
        id: 1000,
      };
    },
// 获取树并默认展开
    created() {
      const vm = this;
      vm.getEnvTree(vm);
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    computed: {
      ...mapState({
        envTree: state => state.app.envTree,
        methodList: state => state.staticParamList.methodList,
      }),
    },
    methods: {
      ...mapActions(['getEnvTree']),
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      rename(data) {
        data.isChangeName = true;
      },
      // 默认前端新建环境收藏夹方法[假新建，不与后端交互] start
      append(data) {
        const vm = this;
        let id = vm.id;
        const newChild = {
          id: id++,
          label: '新建收藏夹',
          isChangeName: false,
          children: []
        };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },
      // 默认前端新建环境收藏夹方法[假新建，不与后端交互] end
      // 默认前端新建环境方法[假新建，不与后端交互] start
      appendEnv(data) {
        const vm = this;
        let id = vm.id;
        const newChild = {
          id: id++,
          label: '新建环境',
          isChangeName: false,
          isLeaf: true,
          children: []
        };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },
      // 默认前端新建环境方法[假新建，不与后端交互] end
      remove_old(node, data) {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      },
      // 重命名回车绑定事件 start
      renameAfter(data){
        const vm = this
        if(data.isLeaf){
          vm.updateEnv(data)
        }else {
          vm.updateFav(data)
        }
      },
      // 重命名回车绑定事件end
      // 收藏夹重命名方法 start
      updateFav(data){
        const vm = this
        vm.treeForm.favLabel = data.label
        axios.post(Api.updateFav, {
          sysHead: {
            serviceCode: 'MbsdAccount',
            messageType: '',
            messageCode: ''
          },
          appHead: {},
          body: {
            favName: vm.treeForm.favLabel,
            favId: vm.editform.favId,
          }
        })
          .then(res => {
            if (res.code === SUCCESS_CODE) {
              data.isChangeName = false
              vm.getEnvTree(vm);
              vm.$message.success('收藏夹重命名成功')
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(function (err) {
              console.log(err);
            }
          );
      },
      // 收藏夹重命名方法 end
      // 环境重命名方法 start
      updateEnv(data){
        const vm = this
        vm.treeForm.label = data.label
        axios.post(Api.updateEnv, {
          sysHead: {
            serviceCode: 'MbsdAccount',
            messageType: '',
            messageCode: ''
          },
          appHead: {},
          body: {
            svrName: vm.treeForm.label,
            svrId: vm.editform.favId,
          }
        })
          .then(res => {
            if (res.code === SUCCESS_CODE) {
              data.isChangeName = false
              vm.getEnvTree(vm);
              vm.$message.success('环境重命名成功')
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(function (err) {
              console.log(err);
            }
          );
      },
      // 环境重命名方法 end
      // 前端新建环境方法 start
      newEnv(data){
        const vm = this;
        vm.editform.dialogFormVisible = true
      },
      // 前端新建环境方法 end
      // 前端新建收藏夹方法 start
      newFav(data){
        const vm = this;
          axios.post(Api.newFav, {
            sysHead: {
              serviceCode: 'MbsdAccount',
              messageType: '',
              messageCode: ''
            },
            appHead: {},
            body: {
              favName: vm.treeForm.favLabel,
              parentId: vm.editform.parentId,
            }
          })
            .then(res => {
              if (res.code === SUCCESS_CODE) {
                vm.getEnvTree(vm);
                vm.$message.success('新增文件夹成功')
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(function (err) {
                console.log(err);
              }
            );
      },
      // 前端新建收藏夹方法 end
      // 删除绑定事件 start
      remove(data){
        const vm = this
        if(data.isLeaf){
          vm.removeEnv(data)
        }else {
          vm.removeFav(data)
        }
      },
      // 删除绑定事件end
      // 前端删除环境方法 start
      removeEnv(data){
        const vm = this;
        axios.post(Api.removeEnv, {
          sysHead: {
            serviceCode: 'MbsdAccount',
            messageType: '',
            messageCode: ''
          },
          appHead: {},
          body: {
            svrId: vm.editform.favId,
          }
        })
          .then(res => {
            if (res.code === SUCCESS_CODE) {
              vm.getEnvTree(vm);
              vm.$message.success('删除环境成功')
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(function (err) {
              console.log(err);
            }
          );
      },
      // 前端删除环境方法 end
      // 前端删除环境方法 start
      removeFav(data){
        const vm = this;
        axios.post(Api.removeFav, {
          sysHead: {
            serviceCode: 'MbsdAccount',
            messageType: '',
            messageCode: ''
          },
          appHead: {},
          body: {
            favId: vm.editform.favId,
          }
        })
          .then(res => {
            if (res.code === SUCCESS_CODE) {
              vm.getEnvTree(vm);
              vm.$message.success('删除收藏夹成功')
            } else {
              this.$message.error(res.message)
            }
          })
          .catch(function (err) {
              console.log(err);
            }
          );
      },
      // 前端删除环境方法 end
      // 前端新建环境页面确定按钮绑定事件 start
      clickButton() {
        const vm = this;
        vm.editform.dialogFormVisible = true
        if (vm.editform.svrIp != ''|| vm.editform.svrPort != ''){
          axios.post(Api.newEnv, {
            sysHead: {
              serviceCode: 'MbsdAccount',
              messageType: '',
              messageCode: ''
            },
            appHead: {},
            body: {
              svrType: vm.editform.svrType,
              svrIp: vm.editform.svrIp,
              svrPort: vm.editform.svrPort,
              svrName: vm.treeForm.label,
              favId: vm.editform.parentId,
              tmplId: vm.editform.tmplId,
              method: vm.editform.method,
            }
          })
            .then(res => {
              if (res.code === SUCCESS_CODE) {
                vm.getEnvTree(vm);
                vm.$message.success('新增成功')
              } else {
                this.$message.error(res.message)
              }
              vm.editform.dialogFormVisible = false
            })
            .catch(function (err) {
                console.log(err);
              }
            );
        }else {
          console.log("默认点击事件")
        }
      },
      // 前端新建环境页面确定按钮绑定事件 end
      // 新增页面跳转
      goRouter: function (node) {
        const vm = this;
        vm.editform.favId = node[this.props.value]
        console.log('默认点击事件为环境' + node[this.props.value]);
        if (node[this.props.isLeaf]) {
          vm.$router.push({
            name: 'env',
            params: {
              id: node[this.props.value],
              label: node[this.props.label],
            }
          });
        } else {
          vm.editform.parentId = node[this.props.value]
          console.log('默认点击事件为文件夹' + node[this.props.value]);
        }
      },
    }
  };
</script>

<style lang='scss' scoped>
  .left-tree {
    border: 1px solid #ebeef5;
    border-radius: 3px;

    .tree-title {
      padding: 10px;
      font-size: 16px;
      font-weight: 600;
      text-align: left;
      border-bottom: 1px solid #ebeef5;
    }

    .fa {
      margin-right: 10px;
    }

    .left-tree-btns {
      margin-left: auto;
    }

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      font-size: 14px;
      padding-right: 8px;

      .el-dropdown-link {
        height: 40px;
        cursor: pointer;
        padding: 12px 15px;
        margin-top: 12px;
      }
    }

    .el-tree-node__content {
      width: auto;
      margin-top: 12px;
      float: right;
      font-family: “Trebuchet MS”, Arial, Helvetica, sans-serif;
      font-size: 14px;
      color: #2a2e33;
      line-height: 25px;
      letter-spacing: 1px;
    }

    .tree-body {
      padding: 1px;
      overflow: auto;
      margin: 1px;
      height: 700px;
      overflow-y: scroll;
      font-size: 22px;
      color: #2a2e33;

      > > > .el-tree-node {
        > .el-tree-node__children {
          height: 30px;
          overflow: visible !important
        }
      }
    }
  }
</style>
<style lang='scss'>
  .left-tree {
    .el-input--mini .el-input__inner {
      height: 20px;
      line-height: 20px;
    }
  }
</style>
